package com.skb.web.controller;

import com.skb.core.model.User;
import com.skb.core.model.UserRole;
import com.skb.core.service.*;
import com.skb.utils.SysLookup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class MainController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleUserService userRoleService;



	@RequestMapping(value = { "/" }, method = RequestMethod.GET)
	public ModelAndView defaultPage(HttpSession session) {
		ModelAndView model = new ModelAndView();
            model.setViewName("user");
//            model.setViewName("redirect:/updateSession");
		return model;
	}

    @Transactional
    @RequestMapping(value = { "/updateSession" }, method = RequestMethod.GET)
    public ModelAndView updateUserSession(HttpSession session) {
        ModelAndView model = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            UserDetails userDetail = (UserDetails) auth.getPrincipal();
            System.out.println(userDetail);
            model.addObject("username", userDetail.getUsername());
            session.setAttribute(SysLookup.SessionKey.USERNAME, userDetail.getUsername());
            User user = userService.getUserDetails(userDetail.getUsername());
            String department = SysLookup.DEPARTMENT.ARCHIVE.toString();// user.getUserDepartment().iterator().next().getDepartment();
            session.setAttribute(SysLookup.SessionKey.DEPARTMENTS, department);
//            session.setAttribute("department", user.getUserDepartment().toString().replaceAll("[\\[\\] ]", ""));
            StringBuilder sb = new StringBuilder();
            for (UserRole userRole : user.getUserRole()) {
                sb.append(userRole.getRole()).append(",");
            }
            if (sb.length() > 2)
            sb.substring(0, sb.length() - 2);
            session.setAttribute(SysLookup.SessionKey.ROLES, sb.toString());
//            session.setAttribute(SysLookup.SessionKey.SESSION_INFO, new SessionInfo(petroOilDocService.countTasks(department),
//                    SysLookup.DEPARTMENT.valueOf(department).getDescription()));
            model.setViewName("redirect:/");
        } else {
            model.setViewName("redirect:/login");
        }
        return model;
    }

	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public ModelAndView adminPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("admin");
		return model;
	}

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView setParamInSession(HttpSession session) {
        ModelAndView model = new ModelAndView();
        session.setAttribute("department", "testDep");
        model.setViewName("403");
        return model;
    }

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout, HttpServletRequest request) {

		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
		}

		if (logout != null) {
			model.addObject("msg", "Zostałeś wylogowany pomyślnie");
		}
		model.setViewName("login");

		return model;
	}

	// customize the error message
	private String getErrorMessage(HttpServletRequest request, String key) {
		Exception exception = (Exception) request.getSession().getAttribute(key);
		String error = "";
		if (exception instanceof BadCredentialsException) {
			error = "Niepoprawny login lub hasło";
		} else if (exception instanceof LockedException) {
			error = exception.getMessage();
		} else {
			error = "Niepoprawny login lub hasło";
		}
		return error;
	}

	// for 403 access denied page
	@RequestMapping(value = "/403", method = RequestMethod.GET)
	public ModelAndView accesssDenied() {
		ModelAndView model = new ModelAndView();

		// check if user is login
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (!(auth instanceof AnonymousAuthenticationToken)) {
			UserDetails userDetail = (UserDetails) auth.getPrincipal();
			System.out.println(userDetail);
			model.addObject("username", userDetail.getUsername());
		}
		model.setViewName("403");
		return model;
	}

}